package com.sky.task;

import com.github.pagehelper.Page;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;
    /**
     * 支付超时任务
     * 1.检测未支付用户是否超出限制
     * 超出支付时间为15分钟
     */
    @Scheduled(cron = "0 * * * * ?")
    public void payTimeOut(){
        //获取当前时间的前十五分钟
        LocalDateTime localDateTime = LocalDateTime.now().minusMinutes(15);
        //查询未支付订单,超时的
        OrdersPageQueryDTO dto = new OrdersPageQueryDTO();
        dto.setStatus(Orders.PENDING_PAYMENT);
        dto.setEndTime(localDateTime);
        Page<Orders> orders = ordersMapper.selectByPage(dto);
        List<Orders> list = orders;
        if (list != null && list.size() > 0) {
            for (Orders orders1 : list) {
                orders1.setStatus(Orders.CANCELLED);
                orders1.setCancelReason("订单支付超时");
                orders1.setCancelTime(LocalDateTime.now());
                ordersMapper.update(orders1);
            }
        }
    }

    /**
     * 派送超时检测任务
     */
    @Scheduled(cron = "0 0 2 * * ?") //每天凌晨2点检查
    public void dispatchTimeOut(){
        Orders orders = new Orders();
        //设置当前时间2点的前两小时
        LocalDateTime localDateTime = LocalDateTime.now().minusHours(2);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS); //状态为派送中
        orders.setCheckoutTime(localDateTime); //时间为检查时间的2小时前
        List<Orders> list = ordersMapper.selectDispatchTimeOut(orders);

        if (list != null && list.size() > 0) {
            for (Orders orders1 : list) {
                orders1.setStatus(Orders.COMPLETED);
                orders1.setDeliveryTime(LocalDateTime.now());
                ordersMapper.update(orders1);
            }
        }
    }
}
